angular.module('infiniteScroll', [])
	.directive('infiniteScroll', [ "$window", "$timeout", function ($window, $timeout) {
		return {
			link: function (scope, element, attrs) {
				var offset = parseInt(attrs.threshold) || 0;
				var e = element[0];

				scope.watchMap = scope.watchMap || {};

				if (attrs.statusKey && !scope.watchMap[attrs.statusKey]) {
					scope.watchMap[attrs.statusKey] = true;

					scope.$watch(attrs.statusKey, function (newVal, oldVal) {
						// 初始化加载完毕
						if (newVal === false) {
							autoExec();
						}
					});
				}

				function autoExec() {
					if (Math.abs(e.scrollHeight - e.clientHeight) < 10) {
						scope[getMethod(attrs.infiniteScroll)](function (err, rtn) {

							if (!err && rtn) {
								autoExec();
							}
						});
					}
				}

				function getMethod(methodStr) {
					return methodStr.replace(/\(.*\)/, '');
				}

				element.bind('scroll', function () {
					if (scope.$eval(attrs.canLoad) && e.scrollTop + e.offsetHeight >= e.scrollHeight - offset) {
						scope.$apply(attrs.infiniteScroll);
					}
				});
			}
		};
	}]);